package yxy.game.pm2.command.soloride;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.SoloRideMessage;
import yxy.game.pm2.module.player.PlayerHandle;
import yxy.game.pm2.module.soloride.RankSoloRide;

import java.util.Collection;

/** 千里走单骑 千里走单骑排行榜 */
@MessageType(proto = Command.SoloRideRank, classtype = SoloRideMessage.SoloRideRankRequest.class)
public class CMD_SoloRideRank extends Command<SoloRideMessage.SoloRideRankRequest> {

	@Override
	public void execute(MessageSource messageSource, SoloRideMessage.SoloRideRankRequest request) {
		String playerCode = messageSource.getTag();

		SoloRideMessage.SoloRideRankResponse.Builder response = SoloRideMessage.SoloRideRankResponse.newBuilder();

		RankSoloRide rankSoloRide = RankSoloRide.getRank(playerCode);
		try {
			Collection<RankEntry> top = rankSoloRide.top(rankSoloRide.topSize());
			int rank = 0;
			for (RankEntry entry : top) {
				String pCode = entry.getKey();
				int best = entry.getValue().intValue();

				SoloRideMessage.RankSoloRide.Builder builder = SoloRideMessage.RankSoloRide.newBuilder();
				builder.setRank(++rank);
				builder.setPlayerInfo(new PlayerHandle().playerSimpleInfo(pCode));
				builder.setBest(best);
				response.addRank(builder);
			}

			{
				int playerRank = 0;
				int best = 0;
				RankEntry entry = rankSoloRide.get(playerCode);
				if (entry != null) {
					playerRank = rankSoloRide.rank(playerCode);
					best = entry.getValue().intValue();
				}

				SoloRideMessage.RankSoloRide.Builder builder = SoloRideMessage.RankSoloRide.newBuilder();
				builder.setRank(playerRank);
				builder.setPlayerInfo(new PlayerHandle().playerSimpleInfo(playerCode));
				builder.setBest(best);
				response.setMy(builder);
			}
			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, SoloRideMessage.SoloRideRankResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}